﻿using FreeSql;
using NoSqlTest.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NoSqlTest
{
    public class FreeSqlContext: DbContext
    {

        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
        public DbSet<ClassGrade> ClassGrades { get; set; }
        public DbSet<MiddleClassCourse> MiddleClassCourses { get; set; }
        public DbSet<MiddleStudentCourse> MiddleStudentCourses { get; set; }

        //每个 DbContext 只触发一次
        protected override void OnModelCreating(ICodeFirst codefirst)
        {
            codefirst.Entity<Student>(eb =>
            {
                eb.HasOne(a => a.Class).HasForeignKey(b => b.ClassId).WithMany(c => c.Students);
            });

            codefirst.Entity<MiddleStudentCourse>(eb =>
            {
                eb.HasOne(a => a.Student).WithMany(t => t.Courses).HasForeignKey(b => b.StudentId);
                eb.HasOne(a => a.Course).WithMany(t => t.Students).HasForeignKey(a => a.CourseId);
            });

            codefirst.Entity<MiddleClassCourse>(eb =>
            {
                eb.HasOne(a => a.Course).WithMany(t => t.ClassStudents).HasForeignKey(a => a.CourseId);
                eb.HasOne(a => a.Class).WithMany(t => t.Students).HasForeignKey(a => a.ClassId);
            });
        }
    }
}
